package cn.wetcland.urban.common.config.exception;

import cn.wetcland.urban.common.AjaxResponse;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@Component
@ControllerAdvice
public class GlobalResponseAdvice implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body,
                                  MethodParameter methodParameter,
                                  MediaType mediaType,
                                  Class aClass,
                                  ServerHttpRequest serverHttpRequest,
                                  ServerHttpResponse serverHttpResponse) {

        // 如果响应结果是 JSON 数据类型
        if (MediaType.APPLICATION_JSON.equalsTypeAndSubtype(mediaType)) {
            if (body instanceof AjaxResponse) {
                /*serverHttpResponse.setStatusCode(HttpStatus.valueOf(
                        ((AjaxResponse) body).getCode()
                ));*/
                return body;
            }
        }

        return body;
    }

}
